package com.alex.common.persistent;

import javax.persistence.EntityManager;

import com.alex.common.exception.AlexCommException;

/**
 * no cache here
 * <p>
 * dao(new Run<Object>() {@Override protected Object
 * run(EntityManager em) return null;} , true);
 * <p>
 * 
 * @author alex
 * 
 */
public abstract class BaseDao {

	protected static abstract class Run<R> {

		protected abstract R run(EntityManager em);
	}

	protected <R> R dao(Run<R> run, boolean isReadOnly) {
		EntityManager em = null;
		try {
			em = JPAEMF.get().createEntityManager();
			if (!isReadOnly) {
				em.getTransaction().begin();
			}
			return run.run(em);
		} catch (Throwable e) {
			throw new AlexCommException(e);
		} finally {
			if (em != null) {
				if (!isReadOnly) {
					em.getTransaction().commit();
				}
				em.close();
			}
		}
	}
}
